import { XxpageContainer } from "@/ui";
import React, { useEffect, useState, useRef, useContext } from "react";
import styles from "./style/authority.module.scss";
import { PlusCircleFilled, CheckOutlined, DeleteOutlined } from '@ant-design/icons';
import { Tabs, Input, message, Space, Button, Form, Spin } from 'antd';
import AuthorityConfig from "./component/authorityConfig";
import AuthorityUserList from "./component/authorityUserList";
import http from "@/utils/http";
import { ADD_ROLE_API, DELETE_ROLES_API, GET_ROLES_LIST_API, SAVE_ROLE_PERMISSION_DATA_API } from "@/api";
import { loadRoleList } from "@/common";
import { Context, globalModal, mobxState } from "@/data";
import { uuid } from "@/utils";
import HookTips from "./component/HookTips";
const { Search } = Input;

/**
 * @description 权限管理配置页面
 * @returns 
 */
const AuthorityView = () => {
    const { modal } = useContext(Context)
    const tipsRef = useRef(null);
    const [keyCodeList, setKeyCodeList] = useState([]);
    const [loading, setLoading] = useState(false);
    const [inputValue, setInputValue] = useState(null);
    const [showInput, setShowInput] = useState(false);
    const [selected, setSelected] = useState({});
    const [active, setActive] = useState("1");
    const [state, setState] = useState({
        total: 0,
        list: []
    })
    const [form] = Form.useForm();
    //添加一个角色
    const onAddRole = (close) => {
        form.validateFields().then(params => {
            http.post({
                url: ADD_ROLE_API,
                params: {
                    ...params
                },
                before: () => { },
                success: res => {
                    message.success("添加成功");
                    form.resetFields();
                    close();
                },
                failure: msg => message.error(msg),
                complete: () => {
                    getRoleList({
                        type: "add"
                    });
                }
            })
        }).catch(err => {
            console.log("校验失败")
        }).then(() => {
            loadRoleList()
        })


    }

    //获取角色列表
    const getRoleList = ({ type = "init" }) => {
        http.get({
            url: GET_ROLES_LIST_API,
            params: {
                current: 1,
                pageSize: 100,
            },
            before: () => setLoading(true),
            success: res => {
                console.log("角色列表获取", res);
                mobxState.updateAllRoles(res?.data?.list);
                setState({
                    total: res?.data?.total || 0,
                    list: res?.data?.list || []
                })
                if (res.data.list.length > 0 && type === "init") {
                    onChangeSelected(res.data.list[0])
                } else if (res.data.list.length > 0 && type === "add") {
                    onChangeSelected(res.data.list[res.data.list.length - 1])
                } else {
                    onChangeSelected(res.data.list[res.data.list.length - 1])
                }
            },
            failure: msg => {
                console.log("error")
            },
            complete: () => {
                setLoading(false)
                // loadRoleList();
            }
        })
    }


    //删除一个角色
    const deleteRole = (roleId) => {
        modal.confirm({
            title: "确定要删除吗？",
            centered: true,
            onOk: () => {
                http.post({
                    url: DELETE_ROLES_API,
                    params: {
                        ids: [roleId],
                    },
                    before: () => { },
                    success: res => {
                        message.success("删除成功");
                    },
                    failure: msg => message.error(msg),
                    complete: () => {
                        getRoleList({})
                    }
                })
            }
        })

    }

    //add class 
    const addClass = () => {
        modal.confirm({
            title: "添加角色",
            centered: true,
            content: <Form form={form}>
                <Form.Item name={"roleName"} label="角色名" rules={[
                    {
                        required: true
                    }
                ]}>
                    <Input placeholder="输入角色名称" />
                </Form.Item>
            </Form>,

            onOk: (close) => onAddRole(close),
        })

    }


    const onChangeSelected = (record) => {
        setSelected({ ...record });
    }

    const onChange = (key) => {
        setActive(key);
    };


    const operations = <Search
        placeholder="搜索成员"
        // onSearch={onSearch}
        style={{
            width: 200,
        }}
    />;

    const onSavePeromission = () => {
        console.log("权限数据：", keyCodeList, selected);
        http.post({
            url: SAVE_ROLE_PERMISSION_DATA_API,
            before: () => { },
            params: {
                role_id: selected.roleId,
                roleName: selected.roleName,
                menu_ids: [...keyCodeList]
            },
            success: res => {
                message.success("保存成功");
            },
            failure: msg => message.error("保存失败"),
            complete: () => {

            }
        })
    }


    const mergeData = (list, allButtonMap) => {
        let res = [];
        list.forEach(item => {
            res.push({
                ...item,
                permissionMark: `m&a_${uuid()}`,
                children: (item.children && item.children.length > 0) && mergeData(item.children, allButtonMap),
                authorityList: (item.children && item.children.length > 0) ? [] : [
                    {
                        menuName: "查看页面",
                        permissionMark: item.permissionMark,

                    },
                    ...item.authorityList
                    // ...getButtonMap(item.key, allButtonMap)
                ]
            })
        })
        return res;
    }

    // 处理数据 给每个数据加上 authorityList 
    const createConfig = (allMenuTreeList = [], allButtonMap = []) => {

        let menuConfig = mergeData(allMenuTreeList, allButtonMap)
        console.log("权限树配置：", menuConfig);
        setMenuConfig(menuConfig);
        // console.log("菜单配置：", JSON.parse(menuConfig));




    }


    // const getMenuTree
    const [menuConfig, setMenuConfig] = useState([]);
    const getMenuTreeConfig = () => {
        http.post({
            url: "/system/menu/getPermissionConfig",
            success: res => {
                createConfig(res?.data.permissions)
            }
        })
    }


    const operationsSavaButton = <Button type="primary" onClick={() => onSavePeromission()}>保存</Button>;
    useEffect(() => {
        getRoleList({ type: "init" });
        getMenuTreeConfig();
    }, [])


    const getRoleMenus = (role_id) => {
        http.post({
            url: "/role/getPermissionForRole",
            params: {
                role_id
            },
            before: () => { },
            success: res => {
                setKeyCodeList(res?.data?.list)
            },
            failure: msg => message.error("权限加载失败"),
            complete: () => { }
        })
    }

    // 每次选中的角色不一样的时候，去获取这个角色对应的权限列表
    useEffect(() => {
        if (selected) {
            getRoleMenus(selected.roleId)
        }
        const { roleName } = selected;
        if (roleName) {
            tipsRef.current.showTips({
                content: "当前选中角色 " + roleName
            })
        }
    }, [selected])
    return (
        <>
            <HookTips onRef={tipsRef} />
            <XxpageContainer>
                <div className={styles.page}>
                    <div className="left">
                        <div className="left-header">
                            <div className="title">角色分组</div>
                            <div className="btn" onClick={addClass}>
                                <PlusCircleFilled style={{ color: "#13c2c2" }} />
                            </div>
                        </div>
                        <div className="list">
                            <Spin spinning={loading}>
                                {
                                    state.list.map((item, key) => {
                                        return <div className="list-item" key={key}>
                                            <Space className="space">
                                                <div className={selected.roleId === item.roleId ? "list-item-container active" : "list-item-container"} onClick={() => onChangeSelected(item)}>
                                                    {item.roleName}
                                                </div>
                                                <div className="deleteBtn" onClick={() => deleteRole(item.roleId)}><DeleteOutlined /></div>
                                            </Space>
                                        </div>
                                    })
                                }
                                {
                                    showInput ? <div className="list-item">
                                        <div className="list-item-container" >
                                            <Space>
                                                <Input
                                                    value={inputValue}
                                                    onChange={(e) => setInputValue(e.target.value)}
                                                    placeholder="输入分组名"
                                                />

                                                <Button type="primary" icon={<CheckOutlined />} onClick={() => onBlurUpdate()} />
                                            </Space>
                                        </div>
                                    </div> : null
                                }
                            </Spin>
                        </div>


                    </div>
                    <div className="right">
                        <div className="right-header">
                            <div className="title">{selected.title}</div>
                            <Tabs
                                className="uself-tabs"
                                tabBarExtraContent={active === "1" ? operations : operationsSavaButton}
                                defaultActiveKey="1"
                                onChange={onChange}
                                items={[
                                    {
                                        label: `成员列表`,
                                        key: '1',
                                    },
                                    {
                                        label: `角色权限`,
                                        key: '2',
                                    },
                                ]}
                            />
                            <div className="uself-table">
                                {
                                    active === "1" ?
                                        <AuthorityUserList
                                            selected={selected} /> :
                                        <AuthorityConfig
                                            menuConfig={menuConfig}
                                            setKeyCodeList={setKeyCodeList}
                                            keyCodeList={keyCodeList}
                                            selected={selected} />
                                }
                            </div>

                        </div>
                    </div>
                </div>
            </XxpageContainer>
        </>
    )
}
export default AuthorityView;